#include <stdio.h>
#include <unistd.h> 
#include <string.h>
#include <sys/types.h> 
#include <sys/wait.h>
#include <assert.h> 
#include <stdlib.h> 
char commondLine[1024];
char* myargv[64];
int sig = 0;
int code = 0;
int main()
{
    int status;
    while(1)
    {
        printf("[用户名@主机名 文件名]$ ");
        fflush(stdout);
        char* str = fgets(commondLine, 1024, stdin); //-1是保证\0被读入
        assert(str != NULL);
        (void)str;
        //把读入的\n替换成\0
        commondLine[strlen(commondLine) - 1] = 0;
        //切割字符串，存入一个指针数组中
        myargv[0] = strtok(commondLine, " ");
        int i = 1;
        //当命令未ls时，自动添加带颜色选项
        if(myargv[0] != NULL && strcmp(myargv[0], "ls") == 0)
        {
            myargv[i++] = (char*)"--color=auto";
        }
        while(myargv[i++] = strtok(NULL, " "));
        //内建/内置命令处理
        if(myargv[0] != NULL && myargv[1] != NULL && strcmp(myargv[0], "cd") == 0)
        {
            chdir(myargv[1]);
            continue;
        }
        if(myargv[0] != NULL && myargv[1] != NULL && strcmp(myargv[0], "echo") == 0)
        {
            if(strcmp(myargv[1], "$?") == 0)
            {
                printf("%d %d\n", code , sig);

            }
            else 
            {
                printf("%s\n", myargv[1]);
            }
            continue;
        }
        

        //如果没有子串了，strtok返回NULL，此时myargv[end] = NULL
//条件编译检查是否截断字符串成功
#ifdef DEBUG 
    for(int j = 0; myargv[j]; ++j)
    {
        printf("argv[%d]: %s\n", j, myargv[j]);
    }
#endif
        pid_t id = fork();
        assert(id != -1);
        if(id == 0)
        {
            execvp(myargv[0], myargv);
            exit(1);
        }
        pid_t ret = waitpid(id, &status, 0);
        assert(ret > 0);
        (void)ret;
        sig = status & 0x7f;
        code = status >> 8 & 0xff;
    }
}

